package com.ziiwee.reduce.describe.creators.controllers;

import com.ziiwee.reduce.describe.DescribeException;
import com.ziiwee.reduce.describe.HandlerDescribe;
import com.ziiwee.reduce.describe.creators.handlers.*;
import com.ziiwee.reduce.describe.utils.DescribeUtil;
import com.ziiwee.reduce.rest.Resource;
import org.springframework.core.ResolvableType;

import java.lang.reflect.AnnotatedElement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ziiwee
 * @data 2020/8/12
 */
public class ResourceControllerDescribeCreator extends AbstractControllerDescribeCreator {

    private final ResolvableType type;

    public ResourceControllerDescribeCreator(Class<?> entityClass) {
        this.type = ResolvableType.forClass(entityClass);
    }


    @Override
    public AnnotatedElement getElement() {
        return type.resolve();
    }

    @Override
    public ResolvableType getDefaultType() {
        return type;
    }

    @Override
    public List<HandlerDescribe> getHandlers() {

        List<ResolvableType> args = DescribeUtil.getTypeArgsByResolvableType(type, Resource.class);
        if (args.size() != 1 || args.get(0).resolve() == null) {
            throw new DescribeException("无法获取泛型参数:" + type);
        }
        List<HandlerDescribe> handlers = new ArrayList<>();
        handlers.add(new RestFindAllHandlerDescribeCreator(type.resolve(), null).create());
        handlers.add(new RestFindOneHandlerDescribeCreator(type.resolve(), args.get(0).resolve(), null).create());
        handlers.add(new RestCreateHandlerDescribeCreator(type.resolve(), null).create());
        handlers.add(new RestUpdateHandlerDescribeCreator(type.resolve(), args.get(0).resolve(), null).create());
        handlers.add(new RestDeleteHandlerDescribeCreator(type.resolve(), args.get(0).resolve(), null).create());
        return handlers;
    }

    @Override
    public ResolvableType getSubjectType() {
        return type;
    }
}
